package com.lgl.job;

import com.lgl.entity.Article;
import com.lgl.service.ArticleService;
import com.lgl.utils.BeanCopyUtils;
import com.lgl.utils.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Component
public class RedisToMysqlJob {
    @Autowired
    private RedisCache redisCache;
    @Autowired
    private ArticleService articleService;
//    每十分钟同步一次数据
//    @Scheduled(cron = "* 0/10 * * * ?")
    public void redisToMysqlJob(){
        Map<String, Integer> cacheMap = redisCache.getCacheMap("article:viewCount");
       List<Article> articles = cacheMap.entrySet()
                .stream()
                .map(article->new Article( Long.valueOf(article.getKey()),Long.valueOf(article.getValue())))
                .collect(Collectors.toList());
//        List<Article> articles = copyBeanMapToList(cacheMap);
        articleService.updateBatchById(articles);
    }
    public static List<Article> copyBeanMapToList(Map<String,Integer> map) {
        List articleList = new ArrayList<Article>();
        map.forEach((n,c)->{
            Article article = new Article();
            article.setId(Long.valueOf(n));
            article.setViewCount(c.longValue());
            articleList.add(article);
        });
        return articleList;
    }
}
